package com.dpwgc.pan.service;

import com.dpwgc.pan.mapper.*;
import com.dpwgc.pan.model.*;
import com.dpwgc.pan.utils.DateUtil;
import com.dpwgc.pan.utils.RedisUtil;
import com.dpwgc.pan.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 用户相关操作
 */
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    DateUtil dateUtil;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    HdfsService hdfsService;

    /**
     * 登录
     * @param phone 用户手机号码
     * @param password 用户密码
     * @return
     */
    public ResultUtil<Object> loginService(String phone,String password){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        //安全加密类
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        if(password.length()<6 || password.length()>20){

            resultUtil.setCode(100);
            resultUtil.setMsg("密码格式违规");
            return resultUtil;
        }

        User user = new User();

        try {
            /**
             * 根据根据手机号码查找用户
             */
            user = userMapper.queryUserByPhone(phone);

            //手机号不存在
            if(user == null){

                resultUtil.setCode(100);
                resultUtil.setMsg("手机号码不存在");
                return resultUtil;
            }
            //手机号存在
            else {

                //密码解密，匹配
                if(encoder.matches(password,user.getPassword())){

                    /* 生成token,并将token存储于redis中，设置过期时间 */
                    String token = UUID.randomUUID().toString().replaceAll("-", "");
                    redisUtil.set(user.getUserId()+"", token,604800);

                    user.setPassword(null);

                    resultUtil.setCode(200);
                    resultUtil.setMsg("登录成功|token:"+token);
                    resultUtil.setData(user);
                    return resultUtil;
                }
            }
            resultUtil.setCode(100);
            resultUtil.setMsg("密码错误");
            return resultUtil;

        }catch (Exception e){

            resultUtil.setCode(100);
            resultUtil.setMsg("登录失败");
            return resultUtil;
        }
    }

    /**
     * 注册
     * @param phone 用户手机号码
     * @param nickName 用户昵称
     * @param password 用户密码
     * @param headImg 用户头像
     * @return
     */
    public ResultUtil<Object> insertUserService(String phone,String nickName,String password,String headImg) throws Exception {

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        if(password.length()<6 || password.length()>20){
            resultUtil.setCode(100);
            resultUtil.setMsg("密码格式违规");
            resultUtil.setData("");
            return resultUtil;
        }
        if(nickName.length()<1 || nickName.length()>10){
            resultUtil.setCode(100);
            resultUtil.setMsg("昵称格式违规");
            resultUtil.setData("");
            return resultUtil;
        }
        if(phone.length()<6 || phone.length()>16){
            resultUtil.setCode(100);
            resultUtil.setMsg("手机号码格式违规");
            resultUtil.setData("");
            return resultUtil;
        }

        //验证用户手机号码是否被注册
        User u = userMapper.queryUserByPhone(phone);
        if(u != null){
            resultUtil.setCode(100);
            resultUtil.setMsg("手机号已被注册");
            resultUtil.setData("");
            return resultUtil;
        }

        //安全加密类
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        User user = new User();

        user.setUserUuid(UUID.randomUUID().toString().replaceAll("-", ""));
        //用户文件存储根目录生成（13位时间戳-用户uuid）
        user.setDataLocation("/"+ System.currentTimeMillis() + "-" + user.getUserUuid());
        //在HDFS中创建该文件夹
        hdfsService.mkdirService(user.getDataLocation());

        user.setPhone(phone);
        user.setNickName(nickName);
        user.setPassword(encoder.encode(password));//对用户密码进行加密
        user.setHeadImg(headImg);
        user.setUserStatus(1);
        user.setCreateTime(dateUtil.getDateTime());
        user.setUpdateTime(dateUtil.getDateTime());
        user.setStorageSize(1000000000);

        userMapper.insert(user);

        resultUtil.setCode(200);
        resultUtil.setMsg("注册成功");
        resultUtil.setData(user.getUserId());
        return resultUtil;
    }

    /**
     * 根据用户id返回用户信息
     * @param userId 用户id
     * @return
     */
    public ResultUtil<Object> queryUserByIdService(int userId){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        User user = userMapper.selectById(userId);
        user.setPassword(null);

        resultUtil.setCode(200);
        resultUtil.setMsg("操作成功");
        resultUtil.setData(user);
        return resultUtil;
    }

    /**
     * 根据用户id修改用户个人信息
     * @param userId 用户id
     * @return
     */
    public ResultUtil<Object> updateUserByIdService(int userId,String phone,String nickName,String headImg){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        User u = userMapper.selectById(userId);

        User user = new User();

        user.setUserId(userId);
        user.setPhone(phone);
        user.setNickName(nickName);
        user.setHeadImg(headImg);

        user.setUserStatus(u.getUserStatus());
        user.setCreateTime(u.getCreateTime());
        user.setPassword(u.getPassword());
        user.setUpdateTime(dateUtil.getDateTime());

        int i = userMapper.updateById(user);

        resultUtil.setCode(200);
        resultUtil.setMsg("操作成功");
        resultUtil.setData(i);
        return resultUtil;
    }

    /**
     * 更改密码
     * @param userId 用户id
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return
     */
    public ResultUtil<Object> updatePasswordService(int userId,String oldPassword,String newPassword){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        //安全加密类
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        User user = userMapper.selectById(userId);
        //原密码匹配
        if(encoder.matches(oldPassword,user.getPassword())){

            //更新密码
            int i = userMapper.updatePassword(userId,encoder.encode(newPassword));
            if(i>0){
                resultUtil.setCode(200);
                resultUtil.setMsg("修改成功");
                return resultUtil;
            }
            else {
                resultUtil.setCode(100);
                resultUtil.setMsg("修改失败");
                return resultUtil;
            }
        }
        else {
            resultUtil.setCode(100);
            resultUtil.setMsg("原密码错误");
            return resultUtil;
        }
    }
}
